# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :channel.py
# @Time      :2022/6/2 0002 16:16
# @Author    :何胜利
import json

from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, reqparse, marshal

from common.model_fields.user import news_fields, channel_fields, collection_fields
from models.user import Channel, UserModel, News, Collection
from common.utils.login_utils import login_required
from models import db

channel_bp = Blueprint("channel_bp", __name__, url_prefix="/news")

api = Api(channel_bp)


# 频道
class UserChannelResource(Resource):
    def get(self):
        channels = Channel.query.all()
        channel = marshal(channels, channel_fields)
        return jsonify(data=channel, message="获取成功", code=200)


# 获取文章信息
class NewsResource(Resource):
    def get(self):
        """根据文章的id 获取文章信息"""
        parser = reqparse.RequestParser()
        parser.add_argument("category")
        args = parser.parse_args()
        cate_id = args["category"]
        print("cate_id>>>>", cate_id)
        news = News.query.filter_by(channel_id=cate_id).all()
        # print("news>>>>>?", news)
        datas = json.loads(json.dumps(marshal(news, news_fields)))
        for new in datas:
            user = UserModel.query.filter_by(uid=new["user_id"]).first()
            new["nick_name"] = user.user_name

        print("datas.....", datas)
        return jsonify(message="ok", code=200, data={"news": datas})


# 获取文章详情
class NewInfo(Resource):
    def get(self, id):
        """根据文章id 获取文章详情"""
        new = News.query.filter_by(nid=id).first()
        # 把有序字典转成字典,然后给每篇文章添加作者信息
        data = json.loads(json.dumps(marshal(new, news_fields)))
        user = UserModel.query.filter_by(uid=new.user_id).first()
        data['nick_name'] = user.user_name
        # 从评论中获取
        comment_data = [{'id': i.cmid, 'art_id': i.article_id,
                         'like_count': i.like_count,
                         "reply_count": i.reply_count,
                         'content': i.content,
                         'comment_length': len(new.comment)} for i in new.comment]
        data['comment'] = comment_data
        return jsonify(message='ok',code=200, data=data)


# 点击收藏
class CollectionResource(Resource):
    @login_required
    def get(self, nid):
        """获取用户id"""
        uid = g.user_id
        collection = Collection.query.filter_by(user_id=uid, news_id=nid).first()
        if not collection:
            # 进行添加
            coll = Collection(user_id=uid, news_id=nid)
            db.session.add(coll)
            db.session.commit()
            News.query.filter_by(nid=nid).update({"is_collection": True})
            db.session.commit()
            return jsonify(message="收藏成功", code=200)
        else:
            Collection.query.filter_by(user_id=uid, news_id=nid).delete()
            # Collection.query.filter_by(user_id=uid, news_id=nid).update({"is_delete": False})
            db.session.commit()
            News.query.filter_by(nid=nid).update({"is_collection": False})
            db.session.commit()
            return jsonify(message="取消收藏成功", code=200)


# 我的收藏
class MyCollection(Resource):

    @login_required
    def get(self):
        uid = g.user_id
        collect = Collection.query.filter_by(user_id=uid).first()
        coll = json.loads(json.dumps(marshal(collect, collection_fields)))
        # print("我的收藏表", coll)
        news = News.query.filter_by(nid=coll["news_id"]).all()
        new = json.loads(json.dumps(marshal(news, news_fields)))
        # print("我的收藏展示", new)
        return jsonify(message="获取成功", code=200, data=new)




api.add_resource(MyCollection, "/mycollect")
api.add_resource(NewInfo, "/info/<int:id>")
api.add_resource(UserChannelResource, "/channels")
api.add_resource(NewsResource, "/channel")
api.add_resource(CollectionResource, "/star/<int:nid>")
